package com.qipay.sp.excutor.aliface;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeOrderSettleRequest;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.alipay.api.response.AlipayTradeOrderSettleResponse;
import com.qipay.baas.model.AlipayTransferLog;
import com.qipay.baas.model.Order;
import com.qipay.mapper.AlipayTransferLogMapper;
import com.qipay.scalar.type.ApiTypeEnum;
import com.qipay.sp.excutor.AbstractExcutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Component
public class AlipaySettleExcutor extends AbstractExcutor {

    private final static String CONFIG_APPID_NAME="appid";
    private final static String CONFIG_ALIPAY_PUBLIC_NAME="rsa_public_key_alipay";
    private final static String CONFIG_RSA_PRIVATE_NAME="rsa_private_key";
    private final static String API_URL="https://openapi.alipay.com/gateway.do";

    @Autowired
    AlipayTransferLogMapper alipayTransferLogMapper;

    @Override
    protected ApiTypeEnum getApiTypeEnum() {
        return ApiTypeEnum.ALIPAY_WAP;
    }

    @Override
    protected Map<String, Object> getApiParams(Order order, Map<String, Object> spconfig, Map<String, Object> extendOrderParams) {
        return extendOrderParams;
    }

    @Override
    protected Map<String, Object> run(Map<String, Object> spconfig, Map<String, Object> params) throws Exception {
        AlipayTransferLog alipayTransferLog = (AlipayTransferLog) params.get("alipayTransferLog");
        Object appId = getVal(spconfig, AlipaySettleExcutor.CONFIG_APPID_NAME);
        Object pid = getVal(spconfig, "pid");
        Object rsaPrivateKey = getVal(spconfig, AlipaySettleExcutor.CONFIG_RSA_PRIVATE_NAME);
        Object alipayPublicKey = getVal(spconfig, AlipaySettleExcutor.CONFIG_ALIPAY_PUBLIC_NAME);
        Object trans_in = getVal(spconfig, "trans_in");;//被分账的账户

        String out_request_no = alipayTransferLog.getTransferNo();
        String tradeNo = alipayTransferLog.getSerialNo();//支付宝流水号
        String amount = new BigDecimal(alipayTransferLog.getAmount()).divide(new BigDecimal(100)).toString();
        String remark = "分账给"+trans_in+",金额为："+amount;

        AlipayClient alipayClient = new DefaultAlipayClient(AlipaySettleExcutor.API_URL, appId.toString(),rsaPrivateKey.toString(),"json","UTF-8",alipayPublicKey.toString(),"RSA2");
        AlipayTradeOrderSettleRequest request = new AlipayTradeOrderSettleRequest();

        request.setBizContent("{" +
                "\"out_request_no\":\""+out_request_no+"\"," +
                "\"trade_no\":\""+tradeNo+"\"," +
                "      \"royalty_parameters\":[{" +
                "        \"trans_out\":\""+pid+"\"," +
                "\"trans_in\":\""+trans_in+"\"," +
                "\"amount\":"+amount+"," +
//                "\"amount_percentage\":99," +
                "\"desc\":\""+remark+"\"" +
                "        }]," +
                "\"operator_id\":\"A0001\"" +
                "  }");
        AlipayTradeOrderSettleResponse response = null;

        Map<String, Object> resultMap = new HashMap<>();
        try {
            response = alipayClient.execute(request);
        }catch (Exception e){
            logger.info("结算接口返回settle-error="+e.getMessage());
            resultMap.put("result_code", "1");
            resultMap.put("message", "支付宝结算接口接口请求失败");
            resultMap.put("alipayTransferLog",alipayTransferLog);
        }
        if(response!=null){
            logger.info("结算接口返回settle-success="+response.getBody());
            //保留响应参数
            alipayTransferLog.setRemark(response.getBody());

            if(response.isSuccess()){
                resultMap.put("result_code", "0");
                alipayTransferLog.setStatus((byte)1);
            } else {
                logger.info("支付宝结算接口接口请求失败："+response.getMsg());
                resultMap.put("result_code", "1");
                resultMap.put("message", "支付宝结算接口请求失败");
                resultMap.put("alipayTransferLog",alipayTransferLog);
            }
            alipayTransferLogMapper.updateByPrimaryKey(alipayTransferLog);
        }
        return resultMap;
    }
}
